package juc.mysynchronized.semaphore;

/**
 * @ClassName FileAccessControl
 * @PackageName juc.mysynchronized.semaphore
 * @projectName myThread
 * @Description TODO
 * @Author games
 * @Date 2025/9/4 下午4:28
 * @Version 1.0
 */
import java.util.concurrent.Semaphore;
import java.util.Random;

class FileAccessControl {
    private final Semaphore fileSemaphore;
    private final Random random = new Random();

    public FileAccessControl(int maxReaders) {
        // 控制同时读取文件的线程数量
        this.fileSemaphore = new Semaphore(maxReaders);
    }

    public void readFile(String fileName) {
        try {
            // 获取文件访问许可
            fileSemaphore.acquire();
            System.out.println(Thread.currentThread().getName() +
                    " 开始读取文件: " + fileName );
            System.out.println(
                    "，当前读取者数=== " + ( fileSemaphore.availablePermits()));
            // 模拟文件读取操作
            Thread.sleep(1000 + random.nextInt(2000));
            //System.out.println(Thread.currentThread().getName() +
            //        " 完成文件读取: " + fileName);

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            // 释放文件访问许可
            fileSemaphore.release();
            System.out.println(
                    "，availablePermits=== " + ( fileSemaphore.availablePermits()));
            System.out.println(Thread.currentThread().getName() +
                    " 释放文件访问权限");
        }
    }

    public static void main(String[] args) {
        FileAccessControl fileAccess = new FileAccessControl(2); // 最多2个线程同时读取

        // 模拟多个线程同时请求读取文件
        for (int i = 1; i <= 5; i++) {
            final String fileName = "document" + i + ".txt";
            new Thread(() -> fileAccess.readFile(fileName), "Reader-" + i).start();
        }

    }
}
